
###*
 # @ngdoc directive
 # @name xoceanApp.directive:ntesModule
 # @description
 # # ntesModule
 # The directive will be used in 'subject-box'.
 # In subjectBox, it needs to be filled with 'topicid' and so on.
###
angular.module('xoceanApp')
  .directive 'ntesModule', (ngDialog, $window, $location, $compile)->
    restrict: 'A'
    scope: true
    compile: (tElement, tAttrs)->
      moduleType = tAttrs.ntesModule
      moduleModel = angular.fromJson(tAttrs.ntesModuleModel)
      # For a problem with some complicated headaches.
      # Purpose: transform <div id="123"></div> to <div id="{{id}}"></div>
      html = tElement.html()
      for key,value of moduleModel
        if key is 'img'
           html = html.replace(new RegExp(value, 'g'), "{{#{key}}}")
        else if key isnt 'title'
          html = html.replace(new RegExp(key + "=" + value, 'g'), "#{key}={{#{key}}}")
          html = html.replace(new RegExp(key + "='" + value, 'g'), "#{key}='{{#{key}}}")
      tElement.html html
      return (scope, element, attrs)->


        # 判断当前模块是否是子模块
        scope.child = false
        scope.child = true if attrs.child

        if moduleModel
          for key,value of moduleModel
            scope[key] = value

        element.on 'mouseenter', (e)->
          return if element[0].querySelector('.hover[ntes-module]') or attrs.hoverIgnore isnt undefined
          # if element[0].querySelector()
          element.addClass('hover').addClass('p-hover')
          parent = (element)->
            _ele = element.parent()
            return if not _ele or _ele.hasClass('ntes-html')
            if _ele.attr('ntes-module')
              _ele.addClass('p-hover')
              _ele[0].querySelector('.p-hover[ntes-module]').classList.remove('p-hover')
            parent(_ele)
            return
          parent(element)
          return 

        element.on 'mouseleave', (e)->
          element.removeClass('hover').removeClass('p-hover')
          return 

          
        element.on 'click', (e)->
          e.preventDefault()
          e.stopPropagation()
          if attrs.ntesModuleModel
            element.addClass('active')
            dialog = ngDialog.open({
              template: 'dialog2'
              scope: scope
            })
            dialog.closePromise.then (data)->
              element.removeClass('active')
              return

          if attrs.ntesModule is 'nav'
            scope.navs = []
            [].slice.call(element.find('a')).forEach (a)->
              scope.navs.push({name:a.textContent, link: a.href})
              return
            dialog = ngDialog.open({
              template: 'dialog1'
              scope: scope
              className: 'ngdialog-theme-middle'
            })
            dialog.closePromise.then (data)->
              element.removeClass('active')
              return

          return
        # 保存对话框内容 
        scope.saveDialogForm = (form, nav)->
          if nav is 'nav'
            # 保存导航栏
            html = ''
            scope.navs.forEach (item)->
              if html is '' 
                html = "<li class=\"first\"><a target=\"_blank\" href=\"#{item.link}\">#{item.name}</a></li>"
              else
                html += "<li><a target=\"_blank\" href=\"#{item.link}\">#{item.name}</a></li>"
            element.find('ul').attr('class', "clearfix nav#{scope.navs.length}").html html
            html = null
          else
            for key of moduleModel
              moduleModel[key] = form[key].$modelValue
            attrs.$set('ntes-module-model', angular.toJson(moduleModel))
            for key,value of moduleModel
              scope[key] = value
            element.removeClass('active')
          return true

        

        # 更换头图样式
        scope.changeStyle = ()->
          dialog  = ngDialog.open({
            template: 'dialog6'
            scope: scope
            className: 'ngdialog-style'
            closeByEscape: false
          })

        scope.saveStyle = (banner)->
          element.after $compile("<div include=\"'#{banner.url}'\"></div>")(scope)
          element.remove()
          return true

        # 删除模块
        scope.delModule = ->
          if scope.child
            element.after $compile('<div add-module child=true class="cms-add-module ntes-hide">+</div>')(scope)
          else if element.next().hasClass('cms-add-module')
            element.next().remove()
          element.remove()
          return

        # 拖拽
        return if attrs.draggable isnt "true"
        element.on 'dragstart', (e)->
          return if $window['dragging']
          e.dataTransfer.effectAllowed = 'move'
          e.dataTransfer.setData('Text', '')
          this.classList.add('dragging')
          $window['dragging'] = this
          return
        element.on 'dragenter', (e)->
          e.preventDefault()
          return if this.parentNode isnt $window['dragging'].parentNode
          this.classList.add('dragover')
          return
        element.on 'dragleave', (e)->
          e.preventDefault()
          this.classList.remove('dragover')
          return if this.parentNode isnt $window['dragging'].parentNode
          return
        element.on 'dragover', (e)->
          e.preventDefault()
          return if this.parentNode isnt $window['dragging'].parentNode
          this.classList.add('dragover')
          return
        element.on 'dragend', (e)->
          e.preventDefault()
          this.classList.remove('dragover')
          $window['dragging']?.classList.remove('dragging')
          return
        element.on 'drop', (e)->
          e.preventDefault()
          return if not $window['dragging']
          $window['dragging'].classList.remove('dragging')
          this.classList.remove('dragging')

          ###
            1. not ($window['dragging'].parentNode.contains(this) and this isnt $window['dragging'].parentNode)
              dragging 与 drop 位于同级DOM
            2. $window['dragging'].contains(this)
              dragging 不能包含 drop
            3. this is $window['dragging'] 
              dragging 与drop不相同
            4. this.classList.contains('cms-add-module')
              drop 不能包含cms-add-module
          ###

          # if not ($window['dragging'].parentNode.contains(this) and this isnt $window['dragging'].parentNode) or $window['dragging'].contains(this) or this is $window['dragging'] or this.classList.contains('cms-add-module')
          #   $window['dragging'] = null
          #   return
          if $window['dragging'].parentNode isnt this.parentNode or $window['dragging'] is this or this.classList.contains('cms-add-module')
            $window['dragging'] = null
            return
          e.dataTransfer.dropEffect = 'move'
          this.classList.remove('dragging')
          this.classList.remove('dragover')
          dragging = angular.element $window['dragging']
          draggingClone = dragging.clone()
          that = angular.element this
          dragging.after draggingClone
          that.after dragging
          draggingClone.after that
          draggingClone.remove()
          delete $window['dragging']
          return
        return






